from db_connect import ConnMysqlSlave
from db_connect import ConnMysql
import aiomysql

class Intermediate():

    def __init__(self, product_id, product_type_id):

        self.product_id = product_id
        self.product_type_id = product_type_id
        # self.result = self.main()

    async def result(self):

        if not (self.product_id and self.product_type_id):
        
            return {
                'status': -1,
                'errorCode': 1101,
                'errorMsg': '参数不能为空',
                'resultBody': None,
            }

        if not (self.product_id.isdigit() and self.product_type_id.isdigit()):

            return {
                'status': -1,
                'errorCode': 1102,
                'errorMsg': '参数必须为数字',
                'resultBody': None,
            }

        async with ConnMysqlSlave().pool.acquire() as c:

            print(dir(c))

            await c.ping()

            async with c.cursor(aiomysql.DictCursor) as cur:

                sql = "SELECT * FROM intermediate_table WHERE product_id=%s AND product_type_id=%s"
                await cur.execute(sql, (self.product_id, self.product_type_id))
                select_info = await cur.fetchone()
                print(select_info)

        if not select_info:

            async with ConnMysql().pool.acquire() as c:

                async with c.cursor(aiomysql.DictCursor) as cur:
                    sql = "INSERT INTO intermediate_table(product_id, product_type_id) VALUES (%s,%s)"
                    await cur.execute(sql, (self.product_id, self.product_type_id))
                    await c.commit()

        return {
            'status': 1,
            'errorCode': None,
            'errorMsg': None,
            'resultBody': 'OK',
        }

